package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Slf4j
@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到了用户端请求 ： {}", request.getRequestURL().toString());

        // 1.获取请求头中的令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        // 2.判断令牌是否存在，如果不存在，则不放行
        if (!StringUtils.hasLength(token)) {
            log.info("用户令牌为空，响应 401");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        // 3.校验令牌，如果校验失败则不放行
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            log.info("解析完用户令牌：{}", claims);
            // 获取当前登录员工的 id
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            // 存入 ThreadLocal 中
            BaseContext.setCurrentId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("用户令牌非法，响应 401");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        // 4.放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 移出当前的登录员工 id，防止内存泄漏
        BaseContext.removeCurrentId();
    }
}
